<?php
/**
 * @Author: king
 * @Last Modified by:   king
 * Date: 2018/6/6
 * Time: 16:16
 */
namespace App\Http\Controllers\Api\v1\Order;

use App\Http\Controllers\Api\v1\Check\CheckController as Auth;
use App\Http\Controllers\Api\BaseController;
use App\Exceptions\ApiException;
use App\Models\Api\AwardUser;
use App\Models\Api\Goods;
use App\Models\Api\Orders as OrdersModel;
use App\Models\Api\Orders;
use App\Models\Api\Recode;


/**
 * @title 命格线订单相关接口
 * @desc 查看文章详情<br/>按页码获取文章列表，每页十条<br/>
 * @url /api/v2/article
 * @version 2.0.0
 * Class Article
 * @package app\api\controller\v2
 */
class CheckOrderController extends BaseController
{
    protected $day_id;
    protected $month_id;
    protected $year_id;

    public function __construct()
    {
        parent::__construct();

        $this->day_id = config('app.day_id');
        $this->month_id = config('app.month_id');
        $this->year_id = config('app.year_id');

    }

    /**
     * 检查命格线是否有未支付的订单  --- 新下订单时
     * @param array $map
     */
    public function check_lines($map = [])
    {
        $rid = $map['rid'];
        $gids = $map['gids'];

        $OrdersModel = new OrdersModel();

        if ($rid && $gids) {
            $where = ['o.uid' => $request->uid, 'og.rid' => $rid, 'o.status' => 0];

            try {
                $order = $this->OrderModel
                    ->from('orders  as o')
                    ->join('orders_goods as og', 'o.id','=','og.oid', 'LEFT')
                    ->whereIn('og.gid',$gids)
                    ->where($where)
                    ->get(['o.id']);
            } catch (\Exception $e) {
                $order = [];
            }

            // 如果有未支付的就删除它..重新下单
            if ($order || !empty($order)) {
                foreach ($order as $k => $v) {
                    try {
                        $OrdersModel->where('id', $v)->update(['is_del' => 1]);
                    } catch (\Exception $e) {

                    }
                }
            }
        }

    }

    /**
     * 检查命格线是否有支付的订单  --- 新下订单时
     * @param array $map
     * @throws ApiException
     */
    public function check_lines_pay($map = [])
    {
        $rid = $map['rid'];
        $gids = $map['gids'];

        $OrdersModel = new OrdersModel();

        if ($rid && $gids) {
            $where = ['o.uid' => $request->uid, 'og.rid' => $rid, 'o.status' => 1];

            try {
                $order = $this->OrderModel
                    ->from('orders as o')
                    ->select('o.id','g.name')
                    ->join('orders_goods as og', 'o.id','=','og.oid', 'LEFT')
                    ->join('goods as g', 'og.gid','=','g.id', 'LEFT')
                    ->whereIn('og.gid',$gids)
                    ->where($where)
                    ->get();
            } catch (\Exception $e) {
                $order = [];
            }

            $name = '';
            // 如果有支付的就提示用户
            if ($order || !empty($order)) {
                foreach ($order as $item) {
                    $name .= $item['name'] . ',';
                }

                throw new ApiException($name . '已购买，请重新确认。', 200, config('code.error'));
            }
        }

    }


    /**
     * 检查运势是否有已支付和未支付的订单  --- 新下订单时
     * @param array $map
     * @throws ApiException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function check_fortunes($map = [])
    {
        $uid = $request->uid;  //用户id
        $rids = explode(',', $map['rids']); // 档案id
        $gid = $map['gid'];
        $start_time = $map['start_time'];
        $fortune_type = $map['fortune_type'] * 1;
        $times = '';

        $OrdersModel = new OrdersModel();
        $RecodeModel = new Recode();
        $GoodsModel = new Goods();
        $AwardUser = new AwardUser();

        //检测当前购买的档案时间是否超出当前时间
        foreach ($rids as $v) {
            $re_info = $RecodeModel->getRecode(['id' => $v]);
            $re_time = strtotime($re_info['year'] . '-' . $re_info['month'] . '-' . $re_info['day'] . ' ' . $re_info['hour'] . ':' . $re_info['minute']);
            if ($re_time >= time())
                throw new ApiException('您当前的档案时间超出现实时间，请重新确认。', 200, config('code.error'));
        }

        //获取当前购买的时间范围
        $good = $GoodsModel->select('expire_time')->where('id', $gid)->first();
        $end_time = strtotime($good['expire_time'], $start_time);

        switch ($fortune_type) {
            case 1:
                $time1 = date('Y-n-j', $start_time);
                $time2 = date('Y-n-j', strtotime('-1 days', $end_time));
                break;
            case 2:
                $time1 = date('Y-n', $start_time);
                $time2 = date('Y-n', strtotime('-1 months', $end_time));
                break;
            case 3:
                $time1 = date('Y', $start_time);
                $time2 = date('Y', strtotime('-1 years', $end_time));
                break;
            default :
                $time1 = '';
                $time2 = '';
        }
        $unlock_times = prDates(['start' => $time1, 'end' => $time2, 'type' => $fortune_type]);

        foreach ($rids as $rid) {
            $rid *= 1;
            //获取当前档案已购买的订单
            $orders = $OrdersModel->fortune_orders(['uid' => $uid, 'rid' => $rid, 'type' => $fortune_type]);

            //购买订单解锁时间
            $unlock_time = [];
            $order_time = [];
            $unlock_time_range = [];

            if ($orders && !empty($orders)) {
                //获取档案解锁的信息
                foreach ($orders as $k => $v) {
                    $extend = json_decode($v['extend'], true);
                    //判断该笔订单是否是活动期间购买的
                    if (isset($extend['expire_time']) && $extend['expire_time']) {
                        $v['expire_time'] = $extend['expire_time'];
                    }
                    //判断该笔订单时日运 -- 月运 -- 年运
                    if ($v['type'] == 1 && $v['type'] == $fortune_type) {
                        $new_start_time = date('Y-n-j', $v['time']);
                        $new_end_time = date('Y-n-j', strtotime('-1 days', strtotime($v['expire_time'], $v['time'])));

                    } elseif ($v['type'] == 2 && $v['type'] == $fortune_type) {
                        $new_start_time = date('Y-n', $v['time']);
                        $new_end_time = date('Y-n', strtotime('-1 days', strtotime($v['expire_time'], $v['time'])));
                    } elseif ($v['type'] == 3 && $v['type'] == $fortune_type) {
                        $new_start_time = date('Y', $v['time']);
                        $new_end_time = date('Y', strtotime('-1 days', strtotime($v['expire_time'], $v['time'])));
                    } else {
                        $new_start_time = '';
                        $new_end_time = '';
                    }

                    if ($new_start_time && $new_end_time) {
                        $unlock_time['start_time'] = $new_start_time;
                        $unlock_time['end_time'] = $new_end_time;

                        $order_time[] = prDates(['start' => $unlock_time['start_time'], 'end' => $unlock_time['end_time'], 'type' => $fortune_type]);
                    }
                }

                //获取档案所有解锁的时间范围
                foreach ($order_time as $k => $v) {
                    foreach ($v as $vv) {
                        $unlock_time_range[] = $vv;
                    }
                }
            }

            //获取中奖纪录
            if (in_array($fortune_type, [2, 3])) {
                $afortune_type = $fortune_type + 1;
            } else {
                $afortune_type = 1;
            }
            $aorders = $AwardUser->get_award_fortune(['uid' => $uid, 'rid' => $rid, 'type' => $afortune_type]);

            //中奖解锁时间
            $award_time = [];
            $unlock_award_time = [];
            $award_time_range = [];

            if ($aorders && !empty($aorders)) {
                //获取用户中奖的信息
                foreach ($aorders as $k => $v) {
                    $extend = json_decode($v['extend'], true);
                    if (in_array($v['aid'], $this->day_id)) {
                        $new_start_time = date('Y-n-j', $extend['award_time']);
                        $new_end_time = date('Y-n-j', strtotime('-1 days', strtotime($v['expire_time'], $extend['award_time'])));
                        $award_fortune_type = 1;
                    } elseif (in_array($v['aid'], $this->month_id)) {
                        $new_start_time = date('Y-n', $extend['award_time']);
                        $new_end_time = date('Y-n', strtotime('-1 days', strtotime($v['expire_time'], $extend['award_time'])));
                        $award_fortune_type = 2;

                    } elseif (in_array($v['aid'], $this->year_id)) {
                        $new_start_time = date('Y', $extend['award_time']);
                        $new_end_time = date('Y', strtotime('-1 days', strtotime($v['expire_time'], $extend['award_time'])));
                        $award_fortune_type = 3;
                    } else {
                        $new_start_time = '';
                        $new_end_time = '';
                        $award_fortune_type = 0;
                    }

                    if ($new_start_time && $new_end_time && $award_fortune_type == $fortune_type) {
                        $award_time['start_time'] = $new_start_time;
                        $award_time['end_time'] = $new_end_time;
                        $unlock_award_time[] = prDates(['start' => $award_time['start_time'], 'end' => $award_time['end_time'], 'type' => $fortune_type]);
                    }
                }

                // 获取当前用户所有中奖解锁的时间
                foreach ($unlock_award_time as $k => $v) {
                    foreach ($v as $vv) {
                        $award_time_range[] = $vv;
                    }
                }
            }

            //合并时间
            $time_range = array_merge($unlock_time_range, $award_time_range);
            //时间去重
            $time_range = array_unique($time_range);
            //重新排序
            asort($time_range);
            //重新索引
            $time_range = array_values($time_range);

            //循环判断当前购买解锁的时间范围是否在已解锁的时间范围内
            foreach ($unlock_times as $item) {
                if (in_array($item, $time_range)) {
                    $times .= $item . ',';
                }
            }

            if ($times) {

                throw new ApiException('您购买的运势时间有重复，请重新确认。', 200, config('code.error'));
            }
        }

        //若解锁时间未重复,判断是否有未解锁的相同订单,进行删除重新下单
        $this->check_fortune_nopay(['rids' => $map['rids'], 'gid' => $map['gid'], 'start_time' => $map['start_time']]);
    }

    /**检查运势是否有未支付的订单  --- 新下订单时
     * @param array $map
     */
    public function check_fortune_nopay($map = [])
    {
        $uid = $request->uid;  //用户id
        $rids = $map['rids']; // 档案id
        $gid = $map['gid'];
        $start_time = $map['start_time'];

        $OrdersModel = new OrdersModel();

        $where = ['or.uid' => $uid, 'or.gid' => $gid, 'fr.time' => $start_time, 'fr.rids' => ['like', '%' . $rids . '%']];

        try {
            $orders = $this->OrderModel
                ->from('orders as or')
                ->select('fr.rids','or.id')
                ->join('fortune as fr', 'or.fid','=','fr.id', 'LEFT')
                ->join('orders_goods as og', 'or.id','=','og.oid', 'LEFT')
                ->where($where)
                ->get();
            $orders = json_decode(json_encode($orders, true), true);
        } catch (\Exception $e) {
            $orders = [];
        }

        // 如果有未支付的订单就删除,重新下单
        if ($orders || !empty($orders)) {
            foreach ($orders as $k => $v) {
                try {
                    $OrdersModel->where('id', $v['id'])->update(['is_del' => 1]);
                } catch (\Exception $e) {
                    \Log::info('判断是否有未支付的运势订单,修改订单状态时:' . $e->getMessage());
                }
            }
        }
    }


    /**
     * 检查该商品是否已经购买  --- 重新支付时
     * @param string $order_id
     * @return string|void
     * @throws ApiException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function check_old_orders($order_id = '')
    {
        $num = substr($order_id, 1, 1);

        switch (intval($num)) {
            case 2:
                $this->check_fortune($order_id);
                break;
            case 3:
                $this->check_line($order_id);
                break;
            case 4:
                $this->check_video($order_id);
                break;
        }
    }

    /**
     * 检查视频是否已购买
     * @param string $order_id
     * @throws ApiException
     */
    public function check_video($order_id = '')
    {
        $where = [
            'order_id' => $order_id,
            'status' => 1
        ];

        $OrdersModel = new OrdersModel();

        try {
            $order = $OrdersModel
                ->where($where)
                ->first();
        } catch (\Exception $e) {
            $order = [];
        }

        if ($order) {
            throw new ApiException('该视频已购买', 200, config('code.error'));
        }

    }


    /**
     * 检查生时矫正和命格线是否已经购买  --- 重新支付时
     * @param string $order_id
     * @return string
     * @throws ApiException
     */
    public function check_line($order_id = '')
    {
        $OrdersModel = new OrdersModel();

        //获取重新支付的商品id
        try {
            $gid = $this->OrderModel
                ->from('orders as o')
                ->select('og.gid','og.rid')
                ->join('orders_goods as og', 'o.id','=','og.oid', 'LEFT')
                ->where(['o.order_id' => $order_id])
                ->first()->toArray();
        } catch (\Exception $e) {
            $gid = [];
        }

        //获取当前档案购买的命格线名称
        try {
            $order = $this->OrderModel
                ->from('orders as o')
                ->join('orders_goods as og', 'o.id','=','og.oid', 'LEFT')
                ->join('goods as g', 'og.gid','=','g.id', 'INNER')
                ->where('o.pay_time', '>', 0)
                ->where('og.rid', $gid['rid'])
                ->whereIn('og.gid',$gid['gid'])
                ->get(['g.name']);
        } catch (\Exception $e) {
            $order = [];
        }

        $order = array_unique(json_decode(json_encode($order, true), true));

        $name = implode(',', $order);

        if (!empty($order) || $order) {
            throw new ApiException($name . '已购买', 200, config('code.error'));
        }

        return;
    }

    /**
     * 检查运势是否已经购买  --- 重新支付时
     * @param string $order_id
     * @return bool
     * @throws ApiException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function check_fortune($order_id = '')
    {
        $where = ['o.order_id' => $order_id];

        $AwardUser = new AwardUser();
        $OrdersModel = new OrdersModel();

        //获取当前档案购买的时间范围
        $orders = $OrdersModel
            ->from('orders as o')
            ->select('o.status','f.extend','f.time','f.rids','f.type','g.expire_time','o.uid')
            ->join('fortune as f', 'o.fid','=','f.id', 'INNER')
            ->join('orders_goods as og', 'o.id','=','og.oid', 'INNER')
            ->join('goods as g', 'og.gid','=','g.id', 'INNER')
            ->where($where)
            ->first();

        $orders = json_decode(json_encode($orders, true), true);

        if ($orders) {
            $rids = explode(',', $orders['rids']);

            $start_time = $orders['time'];
            $end_time = strtotime($orders['expire_time'], $orders['time']);

            switch ($orders['type']) {
                case 1:
                    $time1 = date('Y-n-j', $start_time);
                    $time2 = date('Y-n-j', strtotime('-1 days', $end_time));
                    break;
                case 2:
                    $time1 = date('Y-n', $start_time);
                    $time2 = date('Y-n', strtotime('-1 months', $end_time));
                    break;
                case 3:
                    $time1 = date('Y', $start_time);
                    $time2 = date('Y', strtotime('-1 years', $end_time));
                    break;
                default :
                    $time1 = '';
                    $time2 = '';
            }
            //获取当前订单解锁的时间范围
            $unlock_times = prDates(['start' => $time1, 'end' => $time2, 'type' => $orders['type']]);

            $unlock_time_range = [];
            $award_time_range = [];
            $times = '';
            //获取当前档案购买的订单,已解锁的时间范围
            foreach ($rids as $rid) {
                // 类型转换
                $rid *= 1;
                $new_orders = $OrdersModel->fortune_orders(['uid' => $orders['uid'], 'rid' => $rid, 'type' => $orders['type']]);

                //购买订单解锁时间
                $unlock_time = [];
                $order_time = [];

                if ($new_orders && !empty($new_orders)) {
                    //获取档案解锁的信息
                    foreach ($new_orders as $k => $v) {
                        $extend = json_decode($v['extend'], true);

                        if (isset($extend['expire_time']) && $extend['expire_time']) {
                            $v['expire_time'] = $extend['expire_time'];
                        }
                        if ($v['type'] == 1 && $v['type'] == $orders['type']) {
                            $new_start_time = date('Y-n-j', $v['time']);
                            $new_end_time = date('Y-n-j', strtotime('-1 days', strtotime($v['expire_time'], $v['time'])));

                        } elseif ($v['type'] == 2 && $v['type'] == $orders['type']) {
                            $new_start_time = date('Y-n', $v['time']);
                            $new_end_time = date('Y-n', strtotime('-1 days', strtotime($v['expire_time'], $v['time'])));

                        } elseif ($v['type'] == 3 && $v['type'] == $orders['type']) {
                            $new_start_time = date('Y', $v['time']);
                            $new_end_time = date('Y', strtotime('-1 days', strtotime($v['expire_time'], $v['time'])));
                        } else {
                            $new_start_time = '';
                            $new_end_time = '';
                        }

                        if ($new_start_time && $end_time) {
                            $unlock_time['start_time'] = $new_start_time;
                            $unlock_time['end_time'] = $new_end_time;
                            $order_time[] = prDates(['start' => $unlock_time['start_time'], 'end' => $unlock_time['end_time'], 'type' => $v['type']]);
                        }
                    }
                    foreach ($order_time as $k => $v) {
                        foreach ($v as $vv) {
                            $unlock_time_range[] = $vv;
                        }
                    }
                }

                //获取中奖解锁的时间范围
                if (in_array($orders['type'], [2, 3])) {
                    $orders['type'] = $orders['type'] + 1;
                }
                $aorders = $AwardUser->get_award_fortune(['uid' => $orders['uid'], 'rid' => $rid, 'type' => $orders['type']]);
                //中奖解锁时间
                $award_time = [];
                $unlock_award_time = [];

                if ($aorders && !empty($aorders)) {
                    //获取用户中奖的信息
                    foreach ($aorders as $k => $v) {
                        $extend = json_decode($v['extend'], true);
                        if (in_array($v['aid'], $this->day_id)) {
                            $new_start_time = date('Y-n-j', $extend['award_time']);
                            $new_end_time = date('Y-n-j', strtotime('-1 days', strtotime($v['expire_time'], $extend['award_time'])));
                            $award_fortune_type = 1;
                        } elseif (in_array($v['aid'], $this->month_id)) {
                            $new_start_time = date('Y-n', $extend['award_time']);
                            $new_end_time = date('Y-n', strtotime('-1 days', strtotime($v['expire_time'], $extend['award_time'])));
                            $award_fortune_type = 2;

                        } elseif (in_array($v['aid'], $this->year_id)) {
                            $new_start_time = date('Y', $extend['award_time']);
                            $new_end_time = date('Y', strtotime('-1 days', strtotime($v['expire_time'], $extend['award_time'])));
                            $award_fortune_type = 3;
                        } else {
                            $award_fortune_type = 0;
                            $new_start_time = '';
                            $new_end_time = '';
                        }
                        if ($new_start_time && $new_end_time && $award_fortune_type == $orders['type']) {
                            $award_time['start_time'] = $new_start_time;
                            $award_time['end_time'] = $new_end_time;
                            $unlock_award_time[] = prDates(['start' => $award_time['start_time'], 'end' => $award_time['end_time'], 'type' => $orders['type']]);
                        }
                    }
                    // 获取当前用户中奖解锁的时间
                    foreach ($unlock_award_time as $k => $v) {
                        foreach ($v as $vv) {
                            $award_time_range[] = $vv;
                        }
                    }
                }
            }

            //合并时间
            $time_range = array_merge($unlock_time_range, $award_time_range);
            //时间去重
            $time_range = array_unique($time_range);
            //重新排序
            asort($time_range);
            //重新索引
            $time_range = array_values($time_range);

            foreach ($unlock_times as $item) {
                if (in_array($item, $time_range)) {
                    $times .= $item . ',';
                }
            }
            if ($times) {
//            \think\Log::write('运势已购买:' . $times, 'error', true);
//            \think\Log::write('$orders:' . var_export($orders, true), 'error', true);
//            if (isset($aorders)) \think\Log::write('$aorders:' . var_export($aorders, true), 'error', true);
//            throw new ApiException($times . '运势已购买', 200, config('code.error'));
                throw new ApiException('您购买的运势时间有重复，请重新确认。', 200, config('code.error'));
            }
        }

        return true;
    }

    /**
     * 检查当前视频是否未支付
     * @param array $map
     * @return bool
     */
    public function check_unpaid_video($map = [])
    {
        $uid = $map['uid'];
        $gid = $map['gid'];
        //获取当前用户所有视频订单
        $OrdersModel = new OrdersModel();
        $unpaid_orders = $OrdersModel->video_unpaid_orders(['uid' => $uid]);

        if ($unpaid_orders) {
            foreach ($unpaid_orders as $order) {
                if ($gid == $order['gid']) {
                    $arr = [
                        'is_del' => 1
                    ];
                    $where = [
                        'id' => $order['id'],
                        'uid' => $uid
                    ];
                    try {
                        $OrdersModel::update($arr, $where);
                        // 删除订单缓存
                      (new OrdersModel())->rm_cache(['type' => 3, 'order_id' => $order['order_id'], 'uid' => $uid]);

                    } catch (\Exception $e) {
                        \Log::info('下单时将已存在的未支付的视频订单软删除失败:' . $e->getMessage());
                    }
                }
            }
        }

        return true;
    }

    /**
     * 检查当前视频是否已支付
     * @param array $map
     * @return bool
     * @throws ApiException
     */
    public function check_prepaid_video($map = [])
    {
        $uid = $map['uid'];
        $gid = $map['gid'];
        //获取当前用户所有已支付的视频订单
        $OrdersModel = new OrdersModel();
        $prepaid_order_id = $OrdersModel->video_orders(['uid' => $uid]);
        if ($prepaid_order_id && in_array($gid, $prepaid_order_id)) {
            throw new ApiException('该视频已购买', 200, config('code.error'));
        }

        return true;
    }

}
